package com.automannn.tomcat.practice.springWeb.webStarter;

import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ClassPathResource;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

/**
 * @author chenkh
 * @time 2022/1/18
 */
public class AutomannnHtmlServlet implements Servlet {

    private String htmlFile;

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {

    }

    @Override
    public ServletConfig getServletConfig() {
        return null;
    }

    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {

      htmlFile = ((HttpServletRequest) servletRequest).getServletPath();
      /*xxx: 通过servlet上下文去找资源，由于tomcat-embbed的上下文docBase是临时生成的，相应的资源也没有拷贝过去，因此获取不到资源*/
        /*xxx: 另外，servletContext获取资源的方式是: docBase+url路径，采用的file协议*/
//      URL webResource= servletRequest.getServletContext().getResource(htmlFile);
//      InputStream inputStream= webResource.openStream();
        /*xxx: 此处，为了验证 internalResourceView的可用性，适配一个使用 application作为资源句柄去加载资源，并完成渲染逻辑*/
        ClassPathResource classPathResource = new ClassPathResource(htmlFile);
        InputStream inputStream = classPathResource.getInputStream();
        IOUtils.copy(inputStream,servletResponse.getWriter());
        inputStream.close();
    }

    @Override
    public String getServletInfo() {
        return null;
    }

    @Override
    public void destroy() {

    }
}
